//
//  ViewController.m
//  20-JSONHomeWork
//
//  Created by dllo on 16/8/10.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "ViewController.h"
#import "FindCar.h"
#import "Brandlist.h"
#import "Result.h"
#import "Brand.h"
#import "CarBrandTableViewCell.h"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) FindCar *findCar;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    [self handleData];
}
- (void)handleData {
#pragma mark - 处理数据
    NSString *path = [[NSBundle mainBundle] pathForResource:@"AllCar" ofType:@"json"];
    NSData *pathData = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
    NSDictionary *allCarsDic = [NSJSONSerialization JSONObjectWithData:pathData options:NSJSONReadingMutableContainers error:&error];
    self.findCar = [[FindCar alloc] initWithDic:allCarsDic];
    
}
#pragma mark - 返回每个头视图的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return _findCar.result.brandlist[section].letter;
}
#pragma mark - 返回每个分区的row的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _findCar.result.brandlist[section].list.count;
}
#pragma mark - 返回分区的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _findCar.result.brandlist.count;
}
#pragma mark - 给cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarBrandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarReuse"];
    Brand *brand = _findCar.result.brandlist[indexPath.section].list[indexPath.row];
    cell.carNameLabel.text = brand.name;
    
    return cell;
}

#pragma mark - 索引栏
- (NSArray <NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    
    NSMutableArray *arr = [NSMutableArray array];
    for (Brandlist *brand in _findCar.result.brandlist) {
        [arr addObject:brand.letter];
    }
    return arr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
